{% extends "base.html" %}

{% block title %}
{{ activity.title }} - 活动详情
{% endblock %}

{% block style %}
{{ block.super }}
    <style>
        :root {
            --primary: #FF6B35;
            --secondary: #2A9D8F;
            --light: #F8F9FA;
            --dark: #343A40;
            --accent: #E9C46A;
        }

        body {
            background-color: #f8f9fc;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
        }

        .activity-header {
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            color: white;
            padding: 2.5rem 0;
            margin-bottom: 2rem;
            border-radius: 0 0 20px 20px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
        }

        /* 状态筛选器样式 */
        .status-filter-container {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 2px 15px rgba(0,0,0,0.08);
            border: 1px solid rgba(0,0,0,0.05);
        }

        .status-filter {
            display: flex;
            align-items: center;
            gap: 1rem;
            flex-wrap: wrap;
        }

        .status-filter label {
            font-weight: 600;
            color: var(--dark);
            margin-bottom: 0;
            white-space: nowrap;
        }

        .status-upcoming .status-indicator {
            background: #28a745;
        }

        .status-ongoing .status-indicator {
            background: #ffc107;
        }

        .status-ended .status-indicator {
            background: #6c757d;
        }

        .status-cancelled .status-indicator {
            background: #dc3545;
        }

        /* 活动状态徽章样式 */
        .status-badge {
            padding: 0.5rem 1rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
            background: rgba(255,255,255,0.2);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.3);
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }

        .status-badge.upcoming {
            background: rgba(40, 167, 69, 0.2);
            border-color: rgba(40, 167, 69, 0.3);
        }

        .status-badge.ongoing {
            background: rgba(255, 193, 7, 0.2);
            border-color: rgba(255, 193, 7, 0.3);
        }

        .status-badge.ended {
            background: rgba(108, 117, 125, 0.2);
            border-color: rgba(108, 117, 125, 0.3);
        }

        .status-badge.cancelled {
            background: rgba(220, 53, 69, 0.2);
            border-color: rgba(220, 53, 69, 0.3);
        }

        .status-badge .status-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
        }

        .status-badge.upcoming .status-dot {
            background: #28a745;
        }

        .status-badge.ongoing .status-dot {
            background: #ffc107;
        }

        .status-badge.ended .status-dot {
            background: #6c757d;
        }

        .status-badge.cancelled .status-dot {
            background: #dc3545;
        }

        /* 原有样式保持不变 */
        .activity-cover {
            height: 380px;
            background-size: cover;
            background-position: center;
            border-radius: 16px;
            margin-bottom: 2rem;
            position: relative;
            box-shadow: 0 8px 30px rgba(0,0,0,0.12);
            border: 1px solid rgba(255,255,255,0.2);
        }

        .activity-info-card {
            background: white;
            border-radius: 16px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            margin-bottom: 1.5rem;
            overflow: hidden;
            border: 1px solid rgba(0,0,0,0.05);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        :root {
            --primary: #FF6B35;
            --secondary: #2A9D8F;
            --light: #F8F9FA;
            --dark: #343A40;
            --accent: #E9C46A;
        }

        body {
            background-color: #f8f9fc;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
        }

        .activity-header {
            background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
            color: white;
            padding: 2.5rem 0;
            margin-bottom: 2rem;
            border-radius: 0 0 20px 20px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
        }

        .activity-cover {
            height: 380px;
            background-size: cover;
            background-position: center;
            border-radius: 16px;
            margin-bottom: 2rem;
            position: relative;
            box-shadow: 0 8px 30px rgba(0,0,0,0.12);
            border: 1px solid rgba(255,255,255,0.2);
        }

        .activity-info-card {
            background: white;
            border-radius: 16px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            margin-bottom: 1.5rem;
            overflow: hidden;
            border: 1px solid rgba(0,0,0,0.05);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }

        .activity-info-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 30px rgba(0,0,0,0.12);
        }

        .activity-info-card .card-header {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: white;
            border-bottom: none;
            font-weight: 600;
            padding: 1.25rem 1.5rem;
            font-size: 1.1rem;
            margin: 0;
        }

        .activity-info-card .card-body {
            padding: 1.75rem;
        }

        .info-item {
            display: flex;
            align-items: center;
            margin-bottom: 1rem;
            padding: 1rem 1.25rem;
            border-bottom: 1px solid #f0f0f0;
            transition: background-color 0.2s;
            border-radius: 8px;
        }

        .info-item:hover {
            background-color: #f8f9fa;
        }

        .info-item:last-child {
            border-bottom: none;
            margin-bottom: 0;
        }

        .info-icon {
            width: 44px;
            height: 44px;
            border-radius: 12px;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 1rem;
            flex-shrink: 0;
            color: white;
            font-size: 1.1rem;
        }

        .participant-avatar {
            width: 42px;
            height: 42px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            color: white;
            margin-right: 0.5rem;
            margin-bottom: 0.5rem;
            float: left;
            border: 3px solid white;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            transition: transform 0.2s;
            font-size: 0.9rem;
        }

        .participant-avatar:hover {
            transform: scale(1.1);
        }

        .participant-avatar img {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            object-fit: cover;
        }

        .map-container {
            height: 280px;
            border-radius: 12px;
            overflow: hidden;
            background-color: #e9ecef;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            margin-top: 1rem;
        }

        .review-card {
            border-radius: 12px;
            box-shadow: 0 4px 16px rgba(0,0,0,0.08);
            margin-bottom: 1.25rem;
            background: white;
            overflow: hidden;
            border: 1px solid rgba(0,0,0,0.05);
            transition: transform 0.2s;
        }

        .review-card:hover {
            transform: translateY(-2px);
        }

        .review-header {
            display: flex;
            align-items: center;
            padding: 1.25rem;
            border-bottom: 1px solid #f0f0f0;
            background: #fafbfc;
        }

        .review-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            color: white;
            margin-right: 1rem;
            border: 3px solid white;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            font-size: 1rem;
        }

        .review-avatar img {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            object-fit: cover;
        }

        .review-stars {
            color: #ffc107;
            font-size: 1rem;
            margin: 0.25rem 0;
        }

        .review-images {
            display: flex;
            flex-wrap: wrap;
            gap: 0.75rem;
            margin-top: 1rem;
        }

        .review-image {
            width: 90px;
            height: 90px;
            border-radius: 8px;
            overflow: hidden;
            cursor: pointer;
            transition: transform 0.2s;
        }

        .review-image:hover {
            transform: scale(1.05);
        }

        .review-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .organizer-card {
            background: white;
            border-radius: 16px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            overflow: hidden;
            margin-bottom: 1.5rem;
            border: 1px solid rgba(0,0,0,0.05);
            transition: transform 0.3s;
        }

        .organizer-card:hover {
            transform: translateY(-2px);
        }

        .organizer-card .card-body {
            padding: 1.75rem;
        }

        .organizer-avatar {
            width: 90px;
            height: 90px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.75rem;
            font-weight: bold;
            color: white;
            margin: 0 auto 1.25rem;
            border: 4px solid white;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }

        .organizer-avatar img {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            object-fit: cover;
        }

        .tag {
            display: inline-block;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: white;
            padding: 0.4rem 0.8rem;
            border-radius: 16px;
            font-size: 0.75rem;
            font-weight: 500;
            margin-right: 0.5rem;
            margin-bottom: 0.5rem;
            margin-top: 8px;
        }

        .status-badge {
            padding: 0.5rem 1rem;
            border-radius: 16px;
            font-size: 0.75rem;
            font-weight: 600;
            background: rgba(255,255,255,0.2);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.3);
        }

        .progress {
            height: 10px;
            margin: 0.75rem 0;
            border-radius: 8px;
            background-color: #e9ecef;
            overflow: hidden;
        }

        .progress-bar {
            border-radius: 8px;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
        }

        .related-activity-card {
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
            margin-bottom: 1rem;
            background: white;
            transition: transform 0.3s;
            border: 1px solid rgba(0,0,0,0.05);
        }

        .related-activity-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.12);
        }

        .related-activity-image {
            height: 110px;
            background-size: cover;
            background-position: center;
            position: relative;
        }

        .related-activity-details {
            padding: 1rem;
        }

        .related-activity-title {
            font-weight: 600;
            font-size: 0.85rem;
            margin-bottom: 0.5rem;
            line-height: 1.4;
        }

        /* 私信功能样式 */
        .message-modal .modal-content {
            border-radius: 16px;
            border: none;
            box-shadow: 0 10px 40px rgba(0,0,0,0.1);
        }

        .message-modal .modal-header {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: white;
            border-bottom: none;
            border-radius: 16px 16px 0 0;
            padding: 1.25rem 1.5rem;
        }

        .message-modal .modal-body {
            padding: 1.5rem;
        }

        .message-list {
            max-height: 280px;
            overflow-y: auto;
            margin-bottom: 1rem;
            padding: 0.5rem;
        }

        .message-item {
            padding: 0.875rem 1rem;
            margin-bottom: 0.75rem;
            border-radius: 12px;
            border: 1px solid #e9ecef;
            line-height: 1.5;
        }

        .message-sender {
            background: linear-gradient(135deg, #e3f2fd, #f3e5f5);
            margin-left: 1.5rem;
        }

        .message-receiver {
            background: #f8f9fa;
            margin-right: 1.5rem;
        }

        .message-time {
            font-size: 0.75rem;
            color: #6c757d;
            margin-top: 0.375rem;
        }

        .btn-message {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            border: none;
            color: white;
            padding: 0.5rem 1.25rem;
            border-radius: 20px;
            font-weight: 500;
            transition: all 0.3s;
            font-size: 0.875rem;
        }

        .btn-message:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(255,107,53,0.3);
        }

        .action-buttons {
            display: flex;
            gap: 0.5rem;
            flex-wrap: wrap;
        }

        .btn-action {
            padding: 0.5rem 1rem;
            border-radius: 20px;
            font-weight: 500;
            transition: all 0.3s;
            border: 2px solid transparent;
            font-size: 0.875rem;
        }

        .btn-action:hover {
            transform: translateY(-2px);
        }

        /* 报名按钮样式 */
        .btn-join {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            border: none;
        }

        .btn-join:hover {
            background: linear-gradient(135deg, #218838, #1ea085);
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(40, 167, 69, 0.3);
        }

        .btn-join.joined {
            background: #6c757d;
            color: white;
        }

        .btn-join.joined:hover {
            background: #5a6268;
        }

        /* 关注按钮样式 */
        .btn-follow {
            transition: all 0.3s ease;
        }

        .btn-follow:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        /* 分享下拉菜单 */
        .share-dropdown .dropdown-menu {
            border-radius: 12px;
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
            border: none;
            padding: 0.5rem;
        }

        .share-dropdown .dropdown-item {
            border-radius: 8px;
            padding: 0.75rem 1rem;
            margin: 0.125rem 0;
            display: flex;
            align-items: center;
            transition: all 0.2s;
        }

        .share-dropdown .dropdown-item:hover {
            background-color: #f8f9fa;
        }

        .share-dropdown .dropdown-item i {
            width: 20px;
            margin-right: 0.5rem;
        }

        .share-weibo { color: #e6162d; }
        .share-wechat { color: #07c160; }
        .share-qq { color: #12b7f5; }
        .share-qzone { color: #febd22; }
        .share-douban { color: #2e963d; }

        /* 文字和间距优化 */
        .activity-header h1 {
            margin: 0.5rem 0 0.75rem 0;
            font-size: 2.25rem;
            line-height: 1.2;
        }

        .activity-header .text-white-50 {
            margin: 0.25rem 0;
            font-size: 0.95rem;
        }

        .card-body p {
            margin-bottom: 1rem;
            line-height: 1.7;
        }

        .card-body ul.list-unstyled li {
            margin-bottom: 0.5rem;
            padding: 0.5rem 0;
            line-height: 1.6;
        }

        .card-body h6 {
            margin-bottom: 0.75rem;
            font-size: 1rem;
            font-weight: 600;
        }

        .form-control {
            padding: 0.75rem 1rem;
            border-radius: 10px;
            border: 1px solid #e1e5e9;
            font-size: 0.9rem;
            line-height: 1.5;
        }

        .form-control:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 0.2rem rgba(255, 107, 53, 0.15);
        }

        .alert {
            padding: 1rem 1.25rem;
            border-radius: 10px;
            margin-bottom: 1rem;
            border: none;
            line-height: 1.5;
        }

        .badge {
            padding: 0.4rem 0.75rem;
            font-size: 0.75rem;
            font-weight: 500;
        }

        @media (max-width: 768px) {
            .activity-header {
                padding: 2rem 0;
                border-radius: 0 0 15px 15px;
            }

            .activity-cover {
                height: 220px;
                border-radius: 12px;
                margin-bottom: 1.5rem;
            }

            .action-buttons {
                justify-content: center;
            }

            .activity-header h1 {
                font-size: 1.75rem;
            }

            .activity-info-card .card-body {
                padding: 1.25rem;
            }

            .organizer-card .card-body {
                padding: 1.25rem;
            }
        }

        /* 动画效果 */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .activity-info-card, .organizer-card, .related-activity-card {
            animation: fadeIn 0.6s ease-out;
        }

        /* 加载状态 */
        .loading {
            opacity: 0.6;
            pointer-events: none;
        }

        /* 确保文字有足够的呼吸空间 */
        .text-content {
            line-height: 1.7;
        }

        .text-content p {
            margin-bottom: 1rem;
        }

        .text-content ul, .text-content ol {
            margin-bottom: 1rem;
            padding-left: 1.5rem;
        }

        .text-content li {
            margin-bottom: 0.5rem;
            line-height: 1.6;
        }
        /* 消息限制提示样式 */
        .message-limit-info {
            font-size: 0.8rem;
            margin-right: auto;
        }

        .message-limit-info .text-success {
            color: var(--secondary) !important;
        }

        .message-limit-info .text-warning {
            color: var(--accent) !important;
        }

        .message-limit-info .text-danger {
            color: #dc3545 !important;
        }
    </style>
{% endblock %}

{% block content %}
<!-- 导航栏 - 与首页保持一致 -->
{% include "nav.html" %}

<!-- 活动头部 -->
<div class="activity-header">
    <div class="container">
        <div class="row align-items-center">
            <div class="col-md-8">
                <div class="d-flex align-items-center mb-2">
                    <!-- 动态状态徽章 - 根据每个活动的时间计算 -->
                    <span class="status-badge {{ activity.get_status_class }} me-2">
                        <span class="status-dot"></span>
                        {{ activity.status_display }}
                    </span>
                    <span class="tag me-2">{{ activity.category.name }}</span>
                    <span class="text-white-50">
                        <i class="far fa-eye me-1"></i> {{ activity.views }} 浏览
                    </span>
                </div>
                <h1 class="display-5 fw-bold">{{ activity.title }}</h1>
                <div class="d-flex flex-wrap align-items-center text-white-50 mt-2">
                    <div class="me-3 mb-1">
                        <i class="far fa-calendar-alt me-1"></i>
                        {{ activity.start_time|date:"Y年m月d日 H:i" }}
                    </div>
                    <div class="me-3 mb-1">
                        <i class="fas fa-clock me-1"></i>
                        结束: {{ activity.end_time|date:"Y年m月d日 H:i" }}
                    </div>
                    <div class="me-3 mb-1">
                        <i class="fas fa-map-marker-alt me-1"></i>
                        {{ activity.location_name }}
                    </div>
                    <div class="mb-1">
                        <i class="fas fa-user me-1"></i>
                        组织者: {{ activity.organizer.username }}
                    </div>
                </div>
            </div>
            <div class="col-md-4 text-md-end mt-3 mt-md-0">
                <div class="action-buttons justify-content-md-end">
                    <!-- 分享按钮 -->
                    <div class="share-dropdown dropdown">
                        <button class="btn btn-warning text-white btn-action dropdown-toggle"
                                type="button" data-bs-toggle="dropdown"
                                aria-expanded="false"
                                {% if activity.time_based_status == 'draft' %}disabled{% endif %}>
                            <i class="fas fa-share-alt me-1"></i> 分享
                        </button>
                        <ul class="dropdown-menu">
                            <!-- 补充分享选项，对应已实现的分享函数 -->
                            <li>
                                <a class="dropdown-item share-weibo" href="#" onclick="shareToWeibo(); return false;">
                                    <i class="fab fa-weibo"></i> 微博
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item share-wechat" href="#" onclick="shareToWechat(); return false;">
                                    <i class="fab fa-weixin"></i> 微信
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item share-qq" href="#" onclick="shareToQQ(); return false;">
                                    <i class="fab fa-qq"></i> QQ
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item share-qzone" href="#" onclick="shareToQzone(); return false;">
                                    <i class="fas fa-comment"></i> QQ空间
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item share-douban" href="#" onclick="shareToDouban(); return false;">
                                    <i class="fab fa-douban"></i> 豆瓣
                                </a>
                            </li>
                        </ul>
                    </div>

                    <!-- 报名按钮 - 根据每个活动的时间状态动态控制 -->
                    <button class="btn btn-join btn-action {% if user_joined %}joined{% endif %}"
                        id="join-btn"
                        data-activity-id="{{ activity.id }}"
                        {% if user == activity.organizer or activity.time_based_status == 'ended' or activity.time_based_status == 'cancelled' %}disabled{% endif %}>
                    <i class="fas fa-user-plus me-1"></i>
                    {% if user == activity.organizer %}活动发起者
                    {% elif user_joined %}已报名（点击取消）
                    {% elif activity.is_full %}已满员
                    {% elif activity.time_based_status == 'ended' %}活动已结束
                    {% elif activity.time_based_status == 'cancelled' %}活动已取消
                    {% elif activity.time_based_status == 'ongoing' %}活动进行中
                    {% elif activity.status == 'draft' %}活动未发布
                    {% else %}立即报名{% endif %}
                </button>
                </div>
                <div class="mt-2 text-white-50">
                    <small>
                        已有 <span class="fw-bold text-white current-participants">{{ activity.current_participants }}</span> 人报名，
                        剩余 <span class="fw-bold text-white available-spots">{{ activity.available_spots }}</span> 个名额
                    </small>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="container">
    <div class="row">
        <!-- 左侧内容 -->
        <div class="col-lg-8">
            <!-- 活动封面 -->
            <div class="activity-cover"
                 style="background-image: url('{% if activity.image %}{{ activity.image.url }}{% else %}https://res.cloudinary.com/dqfqah1dn/image/upload/v1640997659/meetlocal/default-activity_zkvqjp.jpg{% endif %}')">
            </div>

            <!-- 活动详情 -->
            <div class="activity-info-card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-info-circle me-2"></i>活动详情</h5>
                </div>
                <div class="card-body text-content">
                    <!-- 时间状态信息 -->
                    <div class="time-status-info mb-4 p-3 rounded" style="background: #f8f9fa;">
                        <div class="row text-center">
                            <div class="col-md-4">
                                <div class="mb-2">
                                    <i class="far fa-calendar-check text-primary fa-lg"></i>
                                </div>
                                <div class="fw-bold">开始时间</div>
                                <div class="text-muted">{{ activity.start_time|date:"Y年m月d日 H:i" }}</div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-2">
                                    <i class="far fa-calendar-times text-primary fa-lg"></i>
                                </div>
                                <div class="fw-bold">结束时间</div>
                                <div class="text-muted">{{ activity.end_time|date:"Y年m月d日 H:i" }}</div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-2">
                                    <i class="fas fa-hourglass-half text-primary fa-lg"></i>
                                </div>
                                <div class="fw-bold">当前状态</div>
                                <div class="text-muted">{{ activity.status_display }}</div>
                            </div>
                        </div>

                        <!-- 倒计时或已进行时间 -->
                        <div class="mt-3 text-center">
                            {% now "Y-m-d H:i:s" as current_time %}
                            {% if activity.time_based_status == 'upcoming' %}
                                <div class="countdown-timer">
                                    <span class="badge bg-warning text-dark">
                                        <i class="fas fa-clock me-1"></i>
                                        距离开始还有: <span id="countdown-timer"></span>
                                    </span>
                                </div>
                            {% elif activity.time_based_status == 'ongoing' %}
                                <div class="progress-timer">
                                    <span class="badge bg-success">
                                        <i class="fas fa-play-circle me-1"></i>
                                        活动进行中
                                    </span>
                                </div>
                            {% elif activity.time_based_status == 'ended' %}
                                <div class="ended-info">
                                    <span class="badge bg-secondary">
                                        <i class="fas fa-flag-checkered me-1"></i>
                                        活动已结束
                                    </span>
                                </div>
                            {% endif %}
                        </div>
                    </div>

                    <!-- 活动描述 -->
                    <div class="activity-description mb-4">
                        <h6 class="text-primary mb-2"><i class="fas fa-file-alt me-2"></i>活动描述</h6>
                        <p class="lead">{{ activity.description|linebreaks }}</p>
                    </div>

                    <!-- 活动亮点 -->
                    {% if activity.highlights %}
                    <div class="activity-highlights mb-4">
                        <h6 class="text-primary mb-2"><i class="fas fa-star me-2"></i>活动亮点</h6>
                        <div class="highlights-content">
                            {{ activity.highlights|linebreaks }}
                        </div>
                    </div>
                    {% endif %}

                    <!-- 行程安排 -->
                    {% if activity.schedule %}
                    <div class="activity-schedule mb-4">
                        <h6 class="text-primary mb-2"><i class="fas fa-list-alt me-2"></i>行程安排</h6>
                        <div class="schedule-content">
                            {{ activity.schedule|linebreaks }}
                        </div>
                    </div>
                    {% endif %}

                    <!-- 注意事项 -->
                    {% if activity.notes %}
                    <div class="activity-notes mb-4">
                        <h6 class="text-primary mb-2"><i class="fas fa-exclamation-circle me-2"></i>注意事项</h6>
                        <div class="notes-content">
                            {{ activity.notes|linebreaks }}
                        </div>
                    </div>
                    {% endif %}
                </div>
            </div>

            <!-- 活动地点 -->
            <div class="activity-info-card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-map-marker-alt me-2"></i>活动地点</h5>
                </div>
                <div class="card-body">
                    <div class="location-info">
                        <h6 class="text-primary mb-2">集合地点</h6>
                        <p class="fs-5 mb-1">{{ activity.location_name }}</p>
                        <small class="text-muted">
                            <i class="fas fa-location-dot me-1"></i>
                            {{ activity.address }}
                        </small>

                        <!-- 显示经纬度信息 -->
                        {% if activity.latitude and activity.longitude %}
                        <div class="coordinates-info mt-2">
                            <small class="text-muted">
                                <i class="fas fa-crosshairs me-1"></i>
                                坐标: {{ activity.latitude|floatformat:6 }}, {{ activity.longitude|floatformat:6 }}
                            </small>
                        </div>
                        {% endif %}
                    </div>

                    {% if activity.latitude and activity.longitude %}
                        <div class="map-container mt-3">
                            <div id="baidu-map" style="width: 100%; height: 280px; border-radius: 8px;"></div>
                        </div>

                        <script>
                            // 百度地图API密钥（与其他页面保持一致）
                            const BAIDU_MAP_AK = 'cb4Sj7ouHojzu3sHgnpJ6uDUWCPYeV3T';
                            let map = null;

                            // 初始化地图
                            function initDetailMap() {
                                // 检查BMap是否已加载
                                if (typeof BMap === 'undefined') {
                                    console.error('BMap未定义，地图API可能未正确加载');
                                    return;
                                }

                                // 创建地图实例
                                map = new BMap.Map("baidu-map");

                                // 使用活动的经纬度作为中心点
                                const point = new BMap.Point({{ activity.longitude }}, {{ activity.latitude }});
                                map.centerAndZoom(point, 15);

                                // 启用滚轮缩放
                                map.enableScrollWheelZoom(true);

                                // 添加基本控件
                                map.addControl(new BMap.NavigationControl());
                                map.addControl(new BMap.ScaleControl());

                                // 添加活动位置标记
                                const marker = new BMap.Marker(point);
                                map.addOverlay(marker);

                                // 添加信息窗口
                                const infoWindow = new BMap.InfoWindow(`
                                    <div style="width: 200px; padding: 10px;">
                                        <h6 style="margin: 0 0 5px 0;">{{ activity.title }}</h6>
                                        <p style="margin: 0; font-size: 12px;">{{ activity.location_name }}</p>
                                    </div>
                                `);
                                marker.addEventListener('click', function() {
                                    this.openInfoWindow(infoWindow);
                                });

                                // 自动打开信息窗口
                                marker.openInfoWindow(infoWindow);
                            }

                            // 动态加载百度地图API
                            function loadBaiduMap() {
                                return new Promise((resolve, reject) => {
                                    // 检查是否已经加载
                                    if (typeof BMap !== 'undefined') {
                                        resolve();
                                        return;
                                    }

                                    const script = document.createElement('script');
                                    script.src = `https://api.map.baidu.com/api?v=3.0&ak=${BAIDU_MAP_AK}&callback=onBMapLoaded`;
                                    script.onerror = () => {
                                        reject(new Error('地图API加载失败，请检查网络连接'));
                                    };
                                    document.head.appendChild(script);

                                    // 设置超时
                                    setTimeout(() => {
                                        if (typeof BMap === 'undefined') {
                                            reject(new Error('地图API加载超时'));
                                        }
                                    }, 10000);
                                });
                            }

                            // 百度地图加载完成回调
                            window.onBMapLoaded = function() {
                                initDetailMap();
                            };

                            // 页面加载完成后初始化地图
                            document.addEventListener('DOMContentLoaded', function() {
                                loadBaiduMap().catch(error => {
                                    console.error('地图加载失败:', error);
                                    const mapContainer = document.getElementById('baidu-map');
                                    if (mapContainer) {
                                        mapContainer.innerHTML = `
                                            <div class="d-flex align-items-center justify-content-center h-100 bg-light">
                                                <p class="text-danger">地图加载失败: ${error.message}</p>
                                            </div>
                                        `;
                                    }
                                });
                            });
                        </script>
                        {% else %}
                        <div class="alert alert-info mt-3">
                            <i class="fas fa-info-circle me-2"></i>该活动暂无地图信息
                        </div>
                        {% endif %}
                </div>
            </div>

            <!-- 参与者 -->
            <div class="activity-info-card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">
                        <i class="fas fa-users me-2"></i>
                        活动参与者 ({{ activity.current_participants }}/{{ activity.max_participants }})
                    </h5>
                    <div class="progress flex-grow-1 mx-3" style="max-width: 180px;">
                        {% widthratio activity.current_participants activity.max_participants 100 as percentage %}
                        <div class="progress-bar" role="progressbar" style="width: {{ percentage }}%"></div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="participants-list">
                        {% for participant in activity.participants.all|slice:":20" %}
                    <div class="participant-avatar" title="{{ participant.user.username }}">
                        {% with avatar_url=participant.user.get_avatar_url %}
                            {% if avatar_url and avatar_url != '/static/images/default-avatar.png' %}
                                <img src="{{ avatar_url }}"
                                     alt="{{ participant.user.username }}"
                                     onerror="handleAvatarError(this)">
                            {% else %}
                                {{ participant.user.username|first|upper }}
                            {% endif %}
                        {% endwith %}
                    </div>
                        {% endfor %}
                        {% if activity.current_participants > 20 %}
                            <div class="participant-avatar" title="+{{ activity.current_participants|add:"-20" }} 更多">
                                <span>+{{ activity.current_participants|add:"-20" }}</span>
                            </div>
                        {% endif %}
                        {% if activity.current_participants == 0 %}
                            <div class="text-center text-muted py-3">
                                <i class="fas fa-users fa-2x mb-2"></i>
                                <p class="mb-0">暂无参与者</p>
                            </div>
                        {% endif %}
                    </div>
                </div>
            </div>

            <!-- 活动评价 -->
            <div class="activity-info-card">
    <div class="card-header">
        <h5 class="mb-0">
            <i class="fas fa-comments me-2"></i>
            活动评价 ({{ avg_rating }}/5)
        </h5>
    </div>
    <div class="card-body">
        <!-- 评论表单 -->
        {% if user.is_authenticated and user_joined %}
            {% if not user_reviewed %}
            <!-- 用户未评分，显示评分表单 -->
            <div class="review-card">
                <div class="card-body">
                    <h6 class="text-primary mb-3">发表评价</h6>
                    <form id="review-form">
                        {% csrf_token %}
                        <div class="mb-3">
                            <label class="form-label fw-semibold">评分</label>
                            <div class="review-stars mt-1">
                                {% for i in "12345" %}
                                    <i class="far fa-star" data-rating="{{ forloop.counter }}"
                                       style="cursor: pointer; margin-right: 5px;"></i>
                                {% endfor %}
                            </div>
                            <input type="hidden" name="rating" id="rating-input" value="5">
                        </div>
                        <div class="mb-3">
                            <label for="review-content" class="form-label fw-semibold">评论内容</label>
                            <textarea class="form-control mt-1" id="review-content" name="comment"
                                      rows="3" placeholder="分享您的活动体验..."></textarea>
                        </div>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-paper-plane me-1"></i>提交评价
                        </button>
                    </form>
                </div>
            </div>
            {% else %}
            <!-- 用户已评分，显示提示信息 -->
            <div class="alert alert-success">
                <div class="d-flex align-items-center">
                    <i class="fas fa-check-circle me-2 fa-lg"></i>
                    <div>
                        <h6 class="mb-1">您已对该活动进行评分</h6>
                        <p class="mb-0 text-muted">
                            您的评分:
                            <span class="text-warning">
                                {% for i in "12345" %}
                                    {% if forloop.counter <= user_review.rating %}
                                        <i class="fas fa-star"></i>
                                    {% else %}
                                        <i class="far fa-star"></i>
                                    {% endif %}
                                {% endfor %}
                                ({{ user_review.rating }}分)
                            </span>
                        </p>
                        {% if user_review.comment %}
                        <p class="mb-0 mt-1">您的评论: "{{ user_review.comment }}"</p>
                        {% endif %}
                    </div>
                </div>
            </div>
            {% endif %}
        {% elif user.is_authenticated %}
        <div class="alert alert-info">
            <i class="fas fa-info-circle me-2"></i>只有参与过活动的用户才能发表评价
        </div>
        {% else %}
        <div class="alert alert-warning">
            <i class="fas fa-exclamation-triangle me-2"></i>
            请<a href="{% url 'login' %}" class="alert-link">登录</a>后发表评价
        </div>
        {% endif %}

        <!-- 评价列表 -->
        <div class="comments-list" id="commentsList">
            {% for review in reviews %}
            <div class="review-card comment" data-review-id="{{ review.id }}">
                <div class="review-header">
                    <div class="review-avatar">
                        {% with avatar_url=review.user.get_avatar_url %}
                            {% if avatar_url and avatar_url != '/static/images/default-avatar.png' %}
                                <img src="{{ avatar_url }}" alt="{{ review.user.username }}" onerror="handleAvatarError(this)">
                            {% else %}
                                {{ review.user.username|first|upper }}
                            {% endif %}
                        {% endwith %}
                    </div>
                    <div class="flex-grow-1">
                        <h6 class="mb-1">{{ review.user.username }}</h6>
                        <div class="review-stars">
                            {% for i in "12345" %}
                                {% if forloop.counter <= review.rating %}
                                    <i class="fas fa-star"></i>
                                {% else %}
                                    <i class="far fa-star"></i>
                                {% endif %}
                            {% endfor %}
                            <span class="text-muted small ms-2">{{ review.created_at|date:"Y-m-d H:i" }}</span>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <p class="mb-0">{{ review.comment }}</p>

                    {% if review.images %}
                    <div class="review-images">
                        {% for img in review.images %}
                        <div class="review-image">
                            <img src="{{ img }}" alt="评论图片">
                        </div>
                        {% endfor %}
                    </div>
                    {% endif %}

                    <div class="comment-actions mt-3">
                        <div class="d-flex justify-content-between align-items-center">
                            <div class="d-flex gap-2">
                                {% if user.is_authenticated %}
                                <button class="comment-like-btn btn btn-sm btn-outline-primary {% if review.user_liked %}liked{% endif %}" data-review-id="{{ review.id }}">
                                    <i class="far fa-thumbs-up me-1"></i>
                                    <span class="comment-like-count">{{ review.likes.count }}</span>
                                </button>
                                <button class="comment-reply-btn btn btn-sm btn-outline-secondary" data-review-id="{{ review.id }}">
                                    <i class="far fa-comment me-1"></i> 回复
                                </button>
                                {% endif %}
                            </div>

                            <div class="d-flex align-items-center gap-2">
                                {% if review.is_verified %}
                                <span class="badge bg-success">
                                    <i class="fas fa-check me-1"></i>已验证参与
                                </span>
                                {% endif %}

                                {% if user.is_authenticated and review.user == user %}
                                <button class="comment-delete-btn btn btn-sm btn-outline-danger" data-review-id="{{ review.id }}">
                                    <i class="fas fa-trash me-1"></i> 删除
                                </button>
                                {% endif %}
                            </div>
                        </div>
                    </div>

                    <!-- 回复表单 -->
                    {% if user.is_authenticated %}
                    <div class="reply-form mt-3" id="replyForm-{{ review.id }}" style="display: none;">
                        <textarea class="form-control reply-input" placeholder="写下你的回复..." rows="2"></textarea>
                        <div class="reply-actions mt-2">
                            <button class="btn btn-primary btn-sm reply-submit" data-review-id="{{ review.id }}">回复</button>
                            <button class="btn btn-secondary btn-sm reply-cancel">取消</button>
                        </div>
                    </div>
                    {% endif %}

                    <!-- 回复列表 -->
                    <div class="replies-list mt-3">
                        {% for reply in review.replies.all %}
                        <div class="review-card comment reply"
                             data-review-id="{{ reply.id }}"
                             data-is-reply="true">
                            <div class="review-header">
                                <div class="review-avatar">
                                    {% with avatar_url=reply.user.get_avatar_url %}
                                        {% if avatar_url and avatar_url != '/static/images/default-avatar.png' %}
                                            <img src="{{ avatar_url }}" alt="{{ reply.user.username }}" onerror="handleAvatarError(this)">
                                        {% else %}
                                            {{ reply.user.username|first|upper }}
                                        {% endif %}
                                    {% endwith %}
                                </div>
                                <div class="flex-grow-1">
                                    <div class="d-flex align-items-center flex-wrap">
                                        <h6 class="mb-0 me-2">{{ reply.user.username }}</h6>
                                        <span class="reply-to text-primary small">
                                            <i class="fas fa-reply me-1"></i>@{{ review.user.username }}
                                        </span>
                                    </div>
                                    <div class="review-stars">
                                        <span class="text-muted small">{{ reply.created_at|date:"Y-m-d H:i" }}</span>
                                    </div>
                                </div>
                            </div>
                            <div class="card-body pt-2">
                                <p class="mb-0 mt-2">{{ reply.content }}</p>

                                <div class="comment-actions mt-2">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div class="d-flex gap-2">
                                            {% if user.is_authenticated %}
                                            <button class="comment-like-btn btn btn-sm btn-outline-primary"
                                                    data-review-id="{{ reply.id }}">
                                                <i class="far fa-thumbs-up me-1"></i>
                                                <span class="comment-like-count">{{ reply.likes.count }}</span>
                                            </button>
                                            {% endif %}
                                        </div>

                                        {% if user.is_authenticated and reply.user == user %}
                                        <button class="comment-delete-btn btn btn-sm btn-outline-danger"
                                                data-review-id="{{ reply.id }}"
                                                data-is-reply="true">
                                            <i class="fas fa-trash me-1"></i> 删除
                                        </button>
                                        {% endif %}
                                    </div>
                                </div>
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                </div>
            </div>
            {% empty %}
            <div class="text-center text-muted py-4">
                <i class="fas fa-comments fa-2x mb-2"></i>
                <p class="mb-0">暂无评价，成为第一个评价的人吧！</p>
            </div>
            {% endfor %}
        </div>
    </div>
</div>
        </div>
 <!-- 右侧侧边栏 -->
        <div class="col-lg-4">
            <!-- 组织者信息 -->
            <div class="organizer-card">
                <div class="card-header">
                    <h5 class="mb-0 text-white">
                        <i class="fas fa-crown me-2"></i>活动组织者
                    </h5>
                </div>
                <div class="card-body text-center">
                    <div class="organizer-avatar">
                        {% with avatar_url=activity.organizer.get_avatar_url %}
                            {% if avatar_url and avatar_url != '/static/images/default-avatar.png' %}
                                <img src="{{ avatar_url }}"
                                     alt="{{ activity.organizer.username }}"
                                     onerror="handleAvatarError(this)">
                            {% else %}
                                {{ activity.organizer.username|first|upper }}
                            {% endif %}
                        {% endwith %}
                    </div>
                    <h5 class="mb-2">{{ activity.organizer.username }}</h5>
                    <p class="text-muted mb-3">
                        <i class="fas fa-calendar-alt me-1"></i>
                        组织了 {{ activity.organizer.organized_activities.count }} 场活动
                    </p>
                    <div class="d-flex gap-2 justify-content-center">
                        <!-- 添加关注按钮 -->
                        {% if user.is_authenticated and user != activity.organizer %}
                        <button class="btn {% if is_following %}btn-primary{% else %}btn-outline-primary{% endif %} btn-sm btn-follow follow-btn"
                                data-user-id="{{ activity.organizer.id }}">
                            <i class="fas {% if is_following %}fa-check{% else %}fa-plus{% endif %} me-1"></i>
                            {% if is_following %}已关注{% else %}关注{% endif %}
                        </button>
                        <button class="btn btn-message btn-sm" data-bs-toggle="modal" data-bs-target="#messageModal">
                            <i class="fas fa-envelope me-1"></i> 私信
                        </button>
                        {% elif user == activity.organizer %}
                        <button class="btn btn-secondary btn-sm" disabled>
                            <i class="fas fa-user me-1"></i> 我的活动
                        </button>
                        {% else %}
                        <button class="btn btn-outline-secondary btn-sm" disabled>
                            <i class="fas fa-sign-in-alt me-1"></i> 登录后关注
                        </button>
                        {% endif %}
                    </div>
                </div>
            </div>

            <!-- 活动统计 - 已移动到右侧侧边栏 -->
            <div class="organizer-card">
                <div class="card-header">
                    <h5 class="mb-0 text-white">
                        <i class="fas fa-chart-bar me-2"></i>活动统计
                    </h5>
                </div>
                <div class="card-body">
                    <div class="info-item">
                        <div class="info-icon">
                            <i class="fas fa-eye"></i>
                        </div>
                        <div>
                            <h6 class="mb-0">{{ activity.views }}</h6>
                            <small class="text-muted">浏览次数</small>
                        </div>
                    </div>
                    <div class="info-item">
                        <div class="info-icon">
                            <i class="fas fa-share-alt"></i>
                        </div>
                        <div>
                            <h6 class="mb-0">{{ activity.shares }}</h6>
                            <small class="text-muted">分享次数</small>
                        </div>
                    </div>
                    <!-- 可以添加其他统计信息 -->
                    <div class="info-item">
                        <div class="info-icon">
                            <i class="fas fa-comments"></i>
                        </div>
                        <div>
                            <h6 class="mb-0">{{ review_count }}</h6>
                            <small class="text-muted">评价数量</small>
                        </div>
                    </div>
                    <div class="info-item">
                        <div class="info-icon">
                            <i class="fas fa-star"></i>
                        </div>
                        <div>
                            <h6 class="mb-0">{{ avg_rating }}/5</h6>
                            <small class="text-muted">平均评分</small>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 相关活动 -->
            <div class="organizer-card">
                <div class="card-header">
                    <h5 class="mb-0 text-white">
                        <i class="fas fa-link me-2"></i>相关活动
                    </h5>
                </div>
                <div class="card-body">
                    {% for related in related_activities %}
                    <div class="related-activity-card">
                        <div class="related-activity-image"
                             style="background-image: url('{% if related.image %}{{ related.image.url }}{% else %}https://res.cloudinary.com/dqfqah1dn/image/upload/v1640997659/meetlocal/default-activity_zkvqjp.jpg{% endif %}')">
                            <div class="tag" style="position: absolute; top: 8px; left: 8px;">
                                {{ related.category.name }}
                            </div>
                        </div>
                        <div class="related-activity-details">
                            <h6 class="related-activity-title">
                                <a href="{% url 'active_detail' related.id %}" class="text-decoration-none text-dark">
                                    {{ related.title }}
                                </a>
                            </h6>
                            <div class="d-flex justify-content-between align-items-center mt-2">
                                <small class="text-muted">
                                    <i class="far fa-calendar me-1"></i>
                                    {{ related.start_time|date:"m月d日" }}
                                </small>
                                <span class="badge bg-primary">
                                    {{ related.current_participants }}/{{ related.max_participants }}
                                </span>
                            </div>
                        </div>
                    </div>
                    {% empty %}
                    <div class="text-center text-muted py-3">
                        <i class="fas fa-calendar-times fa-2x mb-2"></i>
                        <p class="mb-0">暂无相关活动</p>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 私信模态框 -->
<div class="modal fade message-modal" id="messageModal" tabindex="-1" aria-labelledby="messageModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="messageModalLabel">
                    <i class="fas fa-envelope me-2"></i>发送私信给 {{ activity.organizer.username }}
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <!-- 直接设置初始内容，不依赖JS -->
                <div class="message-list" id="messageList">
                    <div class="text-center text-muted py-4">
                        <i class="fas fa-comments fa-2x mb-2"></i>
                        <p class="mb-0">开始与{{ activity.organizer.username }}的对话</p>
                        <small class="text-muted">发送消息开始聊天</small>
                    </div>
                </div>
                <form id="messageForm">
                    {% csrf_token %}
                    <input type="hidden" name="receiver_id" value="{{ activity.organizer.id }}">
                    <div class="mb-3">
                        <textarea class="form-control" id="messageContent" name="content"
                                  rows="3" placeholder="输入您想说的话..." required></textarea>
                    </div>
                    <div class="d-flex justify-content-between align-items-center">
                        <small class="text-muted">私信仅双方可见</small>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-paper-plane me-1"></i>发送
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<script>

    // 活动状态计算函数
    function calculateActivityStatus(startTime, endTime, isCancelled = false) {
        if (isCancelled) {
            return 'cancelled';
        }

        const now = new Date();
        const start = new Date(startTime);
        const end = new Date(endTime);

        if (now < start) {
            return 'upcoming';
        } else if (now >= start && now <= end) {
            return 'ongoing';
        } else {
            return 'ended';
        }
    }

    // 根据活动状态更新页面元素
    function updatePageByStatus(status) {
        const joinBtn = document.getElementById('join-btn');
        const statusBadge = document.querySelector('.status-badge');

        // 根据状态禁用或启用报名按钮
        if (joinBtn) {
            if (status === 'ended' || status === 'cancelled') {
                joinBtn.disabled = true;
            }
        }

        // 更新状态徽章样式
        if (statusBadge) {
            statusBadge.className = 'status-badge me-2 ' + status;
        }

        // 根据状态显示不同的提示信息
        showStatusMessage(status);
    }

    // 显示状态相关提示信息
    function showStatusMessage(status) {
        let message = '';

        switch(status) {
            case 'upcoming':
                message = '活动即将开始，赶快报名参加吧！';
                break;
            case 'ongoing':
                message = '活动正在进行中，欢迎参与！';
                break;
            case 'ended':
                message = '活动已结束，感谢您的关注！';
                break;
            case 'cancelled':
                message = '活动已取消，敬请谅解！';
                break;
        }

        showStatusBanner(message, status);
    }

    // 显示状态横幅
    function showStatusBanner(message, status) {
        // 移除现有的状态横幅
        const existingBanner = document.querySelector('.status-banner');
        if (existingBanner) {
            existingBanner.remove();
        }

        // 创建新的状态横幅
        const banner = document.createElement('div');
        banner.className = `status-banner alert alert-${getStatusAlertType(status)} mb-4`;
        banner.innerHTML = `
            <div class="d-flex align-items-center">
                <i class="fas ${getStatusIcon(status)} me-2"></i>
                <span class="flex-grow-1">${message}</span>
                <button type="button" class="btn-close" onclick="this.parentElement.parentElement.remove()"></button>
            </div>
        `;

        // 插入到活动头部下方
        const activityHeader = document.querySelector('.activity-header');
        if (activityHeader) {
            activityHeader.parentNode.insertBefore(banner, activityHeader.nextSibling);
        }
    }

    // 获取状态对应的提示类型
    function getStatusAlertType(status) {
        switch(status) {
            case 'upcoming': return 'info';
            case 'ongoing': return 'success';
            case 'ended': return 'secondary';
            case 'cancelled': return 'danger';
            default: return 'info';
        }
    }

    // 获取状态对应的图标
    function getStatusIcon(status) {
        switch(status) {
            case 'upcoming': return 'fa-clock';
            case 'ongoing': return 'fa-play-circle';
            case 'ended': return 'fa-flag-checkered';
            case 'cancelled': return 'fa-times-circle';
            default: return 'fa-info-circle';
        }
    }

    // 全局变量存储当前活动ID
    const currentActivityId = {{ activity.id }};
    const csrfToken = '{{ csrf_token }}';
    const currentUser = '{{ user.username }}';

    // 修复关注功能
    document.addEventListener('click', function(e) {
        if (e.target.closest('.btn-follow')) {
            e.preventDefault();
            const button = e.target.closest('.btn-follow');
            toggleFollow(button);
        }
    });

    // 关注/取消关注功能
    function toggleFollow(button) {
        const userId = button.getAttribute('data-user-id');

        if (!userId) {
            showToast('用户ID无效', 'error');
            return;
        }

        button.disabled = true;
        const originalHtml = button.innerHTML;
        const originalClasses = button.className;

        // 显示加载状态
        button.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> 处理中...';

        fetch('/user/toggle_follow/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCsrfToken(),
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify({
                user_id: parseInt(userId)
            })
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(data => {
            console.log('关注响应:', data);
            if (data.success) {
                // 更新按钮状态
                if (data.action === 'followed') {
                    // 关注成功：显示"已关注"
                    button.innerHTML = '<i class="fas fa-check me-1"></i> 已关注';
                    button.classList.remove('btn-outline-primary');
                    button.classList.add('btn-primary');
                    showToast(`已关注 ${data.target_username}`, 'success');
                } else {
                    // 取消关注：显示"关注"
                    button.innerHTML = '<i class="fas fa-plus me-1"></i> 关注';
                    button.classList.remove('btn-primary');
                    button.classList.add('btn-outline-primary');
                    showToast(`已取消关注 ${data.target_username}`, 'info');
                }

                // 发送实时更新通知到个人中心页面
                if (typeof notifyPersonCenter === 'function') {
                    notifyPersonCenter('follow_updated', {
                        userId: parseInt(userId),
                        action: data.action,
                        targetUsername: data.target_username,
                        stats: data.stats
                    });
                }

            } else {
                showToast(data.message || '操作失败', 'error');
                // 恢复原始状态
                button.innerHTML = originalHtml;
                button.className = originalClasses;
            }
        })
        .catch(error => {
            console.error('关注操作失败:', error);
            showToast('网络错误，请重试', 'error');
            // 恢复原始状态
            button.innerHTML = originalHtml;
            button.className = originalClasses;
        })
        .finally(() => {
            button.disabled = false;
        });
    }


    // 获取 CSRF Token
    function getCsrfToken() {
        const csrfTokenElement = document.querySelector('[name=csrfmiddlewaretoken]');
        if (csrfTokenElement) {
            return csrfTokenElement.value;
        }

        // 从 cookie 中获取
        const name = 'csrftoken';
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    // 向个人中心页面发送通知
    function notifyPersonCenter(type, data) {
        const eventData = {
            type: type,
            data: data,
            timestamp: Date.now(),
            source: 'active_detail'
        };

        // 使用 localStorage 作为跨页面通信机制
        localStorage.setItem('person_center_update', JSON.stringify(eventData));

        // 触发 storage 事件（用于同域名下的其他页面监听）
        window.dispatchEvent(new StorageEvent('storage', {
            key: 'person_center_update',
            newValue: JSON.stringify(eventData)
        }));

        console.log('已发送关注更新通知到个人中心:', eventData);
    }

    // 修复：添加评论到DOM
    function addCommentToDOM(commentData, isReply = false, parentReviewId = null) {
        const commentsList = document.getElementById('commentsList');

        if (isReply && parentReviewId) {
            // 添加到回复列表
            const parentReview = document.querySelector(`.comment[data-review-id="${parentReviewId}"]`);
            let repliesList = parentReview.querySelector('.replies-list');

            if (!repliesList) {
                repliesList = document.createElement('div');
                repliesList.className = 'replies-list mt-3';
                parentReview.querySelector('.card-body').appendChild(repliesList);
            }

            const replyElement = createReplyElement(commentData);
            repliesList.appendChild(replyElement);
            animateElement(replyElement);
        } else {
            // 添加主评论
            if (commentsList.querySelector('.text-center.text-muted')) {
                commentsList.innerHTML = '';
            }

            const commentElement = createCommentElement(commentData);
            commentsList.insertBefore(commentElement, commentsList.firstChild);
            animateElement(commentElement);
        }
    }

    // 修复：创建评论元素
    function createCommentElement(commentData) {
        const commentDiv = document.createElement('div');
        commentDiv.className = 'review-card comment';
        commentDiv.setAttribute('data-review-id', commentData.id);

        // 处理头像显示 - 支持多种头像来源
        let avatarHtml;
        const avatarUrl = getAvatarUrl(commentData);
        if (avatarUrl || commentData.user_avatar) {
            avatarHtml = `<img src="${avatarUrl || commentData.user_avatar}" alt="${commentData.username}" onerror="handleAvatarError(this)">`;
        } else {
            avatarHtml = commentData.username.charAt(0).toUpperCase();
        }

        commentDiv.innerHTML = `
            <div class="review-header">
                <div class="review-avatar">
                    ${avatarHtml}
                </div>
                <div class="flex-grow-1">
                    <h6 class="mb-1">${commentData.username}</h6>
                    <div class="review-stars">
                        ${Array.from({length: 5}, (_, i) =>
                            i < commentData.rating ?
                            '<i class="fas fa-star"></i>' :
                            '<i class="far fa-star"></i>'
                        ).join('')}
                        <span class="text-muted small ms-2">${commentData.created_at}</span>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <p class="mb-0">${escapeHtml(commentData.comment)}</p>

                <div class="comment-actions mt-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="d-flex gap-2">
                            ${currentUser ? `
                            <button class="comment-like-btn btn btn-sm btn-outline-primary" data-review-id="${commentData.id}">
                                <i class="far fa-thumbs-up me-1"></i>
                                <span class="comment-like-count">${commentData.likes_count || 0}</span>
                            </button>
                            <button class="comment-reply-btn btn btn-sm btn-outline-secondary" data-review-id="${commentData.id}">
                                <i class="far fa-comment me-1"></i> 回复
                            </button>
                            ` : ''}
                        </div>

                        <div class="d-flex align-items-center gap-2">
                            ${commentData.is_verified ? `
                            <span class="badge bg-success">
                                <i class="fas fa-check me-1"></i>已验证参与
                            </span>
                            ` : ''}

                            ${commentData.is_author ? `
                            <button class="comment-delete-btn btn btn-sm btn-outline-danger" data-review-id="${commentData.id}">
                                <i class="fas fa-trash me-1"></i> 删除
                            </button>
                            ` : ''}
                        </div>
                    </div>
                </div>

                ${currentUser ? `
                <div class="reply-form mt-3" id="replyForm-${commentData.id}" style="display: none;">
                    <textarea class="form-control reply-input" placeholder="写下你的回复..." rows="2"></textarea>
                    <div class="reply-actions mt-2">
                        <button class="btn btn-primary btn-sm reply-submit" data-review-id="${commentData.id}">回复</button>
                        <button class="btn btn-secondary btn-sm reply-cancel">取消</button>
                    </div>
                </div>
                ` : ''}

                <div class="replies-list mt-3"></div>
            </div>
        `;

        return commentDiv;
    }

    // 修复：创建回复元素
    function createReplyElement(replyData) {
        const replyDiv = document.createElement('div');
        replyDiv.className = 'review-card comment reply';
        replyDiv.setAttribute('data-review-id', replyData.id);
        replyDiv.setAttribute('data-is-reply', 'true');

        // 处理回复头像显示 - 支持多种头像来源
        let replyAvatarHtml;
        const replyAvatarUrl = getAvatarUrl(replyData);
        if (replyAvatarUrl || replyData.user_avatar) {
            replyAvatarHtml = `<img src="${replyAvatarUrl || replyData.user_avatar}" alt="${replyData.username}" class="avatar-img" onerror="handleAvatarError(this)">`;
        } else {
            replyAvatarHtml = replyData.username.charAt(0).toUpperCase();
        }
        
        replyDiv.innerHTML = `
            <div class="review-header">
                <div class="review-avatar">
                    ${replyAvatarHtml}
                </div>
                <div class="flex-grow-1">
                    <h6 class="mb-1">${replyData.username}</h6>
                    <div class="review-stars">
                        <span class="text-muted small">${replyData.created_at}</span>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <p class="mb-0">${escapeHtml(replyData.content || replyData.comment)}</p>

                <div class="comment-actions mt-2">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="d-flex gap-2">
                            ${currentUser ? `
                            <button class="comment-like-btn btn btn-sm btn-outline-primary" data-review-id="${replyData.id}">
                                <i class="far fa-thumbs-up me-1"></i>
                                <span class="comment-like-count">${replyData.likes_count || 0}</span>
                            </button>
                            ` : ''}
                        </div>

                        ${replyData.is_author ? `
                        <button class="comment-delete-btn btn btn-sm btn-outline-danger" data-review-id="${replyData.id}" data-is-reply="true">
                            <i class="fas fa-trash me-1"></i> 删除
                        </button>
                        ` : ''}
                    </div>
                </div>
            </div>
        `;

        return replyDiv;
    }

    // 修复：初始化评论功能
    function initCommentFunctions() {
        // 绑定评论列表点击事件（事件委托）
        const commentsList = document.getElementById('commentsList');
        if (commentsList) {
            commentsList.addEventListener('click', handleCommentAction);
        }

        // 初始化回复功能
        initReplyFunctions();

        // 初始化评分功能
        initRatingStars();

        console.log('评论功能初始化完成');
    }

    // 修复：处理评论相关操作
    function handleCommentAction(event) {
        // 处理删除评论
        if (event.target.closest('.comment-delete-btn')) {
            const deleteBtn = event.target.closest('.comment-delete-btn');
            const reviewId = deleteBtn.getAttribute('data-review-id');
            const isReply = deleteBtn.getAttribute('data-is-reply') === 'true';
            const commentElement = deleteBtn.closest('.comment');

            if (reviewId && confirm('确定要删除这条内容吗？')) {
                deleteReview(reviewId, commentElement, isReply);
            }
            return;
        }

        // 处理回复按钮点击
        if (event.target.closest('.comment-reply-btn')) {
            const replyBtn = event.target.closest('.comment-reply-btn');
            const reviewId = replyBtn.getAttribute('data-review-id');
            const replyForm = document.getElementById(`replyForm-${reviewId}`);

            // 隐藏其他回复表单
            document.querySelectorAll('.reply-form').forEach(form => {
                if (form.id !== `replyForm-${reviewId}`) {
                    form.style.display = 'none';
                }
            });

            // 切换当前回复表单显示
            if (replyForm.style.display === 'none') {
                replyForm.style.display = 'block';
                replyForm.querySelector('.reply-input').focus();
            } else {
                replyForm.style.display = 'none';
            }
            return;
        }

        // 处理评论点赞点击
        if (event.target.closest('.comment-like-btn')) {
            const likeBtn = event.target.closest('.comment-like-btn');
            const reviewId = likeBtn.getAttribute('data-review-id');
            toggleReviewLike(reviewId, likeBtn);
            return;
        }
    }

    // 初始化评分星星
    function initRatingStars() {
        const stars = document.querySelectorAll('.review-stars i[data-rating]');
        const ratingInput = document.getElementById('rating-input');

        if (stars.length > 0 && ratingInput) {
            stars.forEach(star => {
                star.addEventListener('click', function() {
                    const rating = this.getAttribute('data-rating');
                    ratingInput.value = rating;

                    stars.forEach(s => {
                        if (s.getAttribute('data-rating') <= rating) {
                            s.classList.remove('far');
                            s.classList.add('fas');
                        } else {
                            s.classList.remove('fas');
                            s.classList.add('far');
                        }
                    });
                });
            });
        }
    }

    // 删除评价
    function deleteReview(reviewId, commentElement, isReply = false) {
    const formData = new FormData();
    formData.append('csrfmiddlewaretoken', csrfToken);
    formData.append('is_reply', isReply.toString());

    fetch(`/meet/review/${reviewId}/delete/`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': csrfToken,
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            commentElement.remove();
            checkEmptyReviews();
            showToast(data.message || '删除成功', 'success');
        } else {
            showToast(data.message || '删除失败', 'error');
        }
    })
    .catch(error => {
        console.error('删除失败:', error);
        showToast('删除失败，请重试', 'error');
    });
}

    // 修复：点赞功能
    function toggleReviewLike(reviewId, likeBtn) {
    const isReply = likeBtn.closest('.reply') !== null;

    // 乐观更新
    const likeCountElement = likeBtn.querySelector('.comment-like-count');
    let currentCount = parseInt(likeCountElement.textContent) || 0;
    const wasLiked = likeBtn.classList.contains('liked');

    if (wasLiked) {
        likeBtn.classList.remove('liked');
        likeCountElement.textContent = Math.max(0, currentCount - 1);
    } else {
        likeBtn.classList.add('liked');
        likeCountElement.textContent = currentCount + 1;
    }

    // 发送请求
    const formData = new FormData();
    formData.append('is_reply', isReply.toString());

    fetch(`/meet/review/${reviewId}/like/`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': csrfToken,
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            likeBtn.classList.toggle('liked', data.liked);
            likeBtn.querySelector('.comment-like-count').textContent = data.likes_count;
        } else {
            // 回滚
            likeBtn.classList.toggle('liked', !wasLiked);
            likeCountElement.textContent = currentCount;
            showToast(data.message || '操作失败', 'error');
        }
    })
    .catch(error => {
        console.error('点赞失败:', error);
        likeBtn.classList.toggle('liked', !wasLiked);
        likeCountElement.textContent = currentCount;
        showToast('操作失败，请重试', 'error');
    });
}

    // 初始化回复功能
    function initReplyFunctions() {
        // 绑定回复取消按钮
        document.querySelectorAll('.reply-cancel').forEach(btn => {
            btn.addEventListener('click', function() {
                const replyForm = this.closest('.reply-form');
                replyForm.style.display = 'none';
                replyForm.querySelector('.reply-input').value = '';
            });
        });

        // 绑定回复提交按钮
        document.querySelectorAll('.reply-submit').forEach(btn => {
            btn.addEventListener('click', function() {
                const reviewId = this.getAttribute('data-review-id');
                handleReplySubmit(reviewId);
            });
        });
    }

    // 修复：处理回复提交
    function handleReplySubmit(parentReviewId) {
        const replyForm = document.getElementById(`replyForm-${parentReviewId}`);
        const replyInput = replyForm.querySelector('.reply-input');
        const content = replyInput.value.trim();

        if (!content) {
            showToast('请输入回复内容', 'error');
            return;
        }

        const submitBtn = replyForm.querySelector('.reply-submit');
        submitBtn.disabled = true;
        submitBtn.textContent = '回复中...';

        // 使用正确的回复路径
        fetch(`/meet/review/${parentReviewId}/reply/`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrfToken,
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify({
                content: content
            })
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                replyInput.value = '';
                replyForm.style.display = 'none';

                if (data.reply) {
                    // 添加回复到DOM
                    addCommentToDOM(data.reply, true, parentReviewId);
                }
                showToast('回复发布成功', 'success');
            } else {
                showToast(data.message || '回复失败', 'error');
            }
        })
        .catch(error => {
            console.error('回复失败:', error);
            showToast('回复失败，请重试', 'error');
        })
        .finally(() => {
            submitBtn.disabled = false;
            submitBtn.textContent = '回复';
        });
    }

    // 修复：评论表单提交
    let isSubmittingReview = false;

    const reviewForm = document.getElementById('review-form');
    if (reviewForm) {
        reviewForm.addEventListener('submit', function(e) {
            e.preventDefault();

            // 防止重复提交
            if (isSubmittingReview) {
                showToast('正在提交中，请稍候...', 'info');
                return;
            }

            const formData = new FormData(this);
            const button = this.querySelector('button[type="submit"]');
            const rating = parseInt(formData.get('rating') || 5);
            const comment = formData.get('comment') || '';

            if (!comment.trim()) {
                showToast('评论内容不能为空', 'error');
                return;
            }

            isSubmittingReview = true;
            button.classList.add('loading');
            button.disabled = true;
            button.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>提交中...';

            // 使用正确的URL
            const reviewUrl = "{% url 'add_review' activity_id=activity.id %}";

            fetch(reviewUrl, {
                method: 'POST',
                headers: {
                    'X-CSRFToken': '{{ csrf_token }}',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    showToast(data.message, 'success');
                    this.reset();

                    // 重置星星评分
                    const stars = this.querySelectorAll('.review-stars i[data-rating]');
                    stars.forEach((star, index) => {
                        if (index < 5) {
                            star.classList.remove('fas');
                            star.classList.add('far');
                        }
                    });
                    document.getElementById('rating-input').value = '5';

                    if (data.review) {
                        // 添加新评论到DOM
                        addCommentToDOM(data.review, data.is_reply, data.parent_review_id);

                        // 如果是主评论，隐藏表单并显示已评价提示
                        if (!data.is_reply) {
                            showUserReviewedMessage(data.review);
                        }
                    }
                } else {
                    showToast(data.message, 'error');
                }
            })
            .catch(error => {
                console.error('评价提交错误:', error);
                showToast('提交失败，请重试', 'error');
            })
            .finally(() => {
                isSubmittingReview = false;
                button.classList.remove('loading');
                button.disabled = false;
                button.innerHTML = '<i class="fas fa-paper-plane me-1"></i>提交评价';
            });
        });
    }

    // 显示用户已评分的提示信息
    function showUserReviewedMessage(reviewData) {
        const reviewSection = document.querySelector('.activity-info-card .card-body');
        const reviewForm = document.getElementById('review-form');

        if (reviewForm && reviewSection) {
            // 创建已评分提示
            const reviewedAlert = document.createElement('div');
            reviewedAlert.className = 'alert alert-success';
            reviewedAlert.innerHTML = `
                <div class="d-flex align-items-center">
                    <i class="fas fa-check-circle me-2 fa-lg"></i>
                    <div>
                        <h6 class="mb-1">您已对该活动进行评分</h6>
                        <p class="mb-0 text-muted">
                            您的评分:
                            <span class="text-warning">
                                ${Array.from({length: 5}, (_, i) =>
                                    i < reviewData.rating ?
                                    '<i class="fas fa-star"></i>' :
                                    '<i class="far fa-star"></i>'
                                ).join('')}
                                (${reviewData.rating}分)
                            </span>
                        </p>
                        ${reviewData.comment ?
                        `<p class="mb-0 mt-1">您的评论: "${reviewData.comment}"</p>` : ''}
                    </div>
                </div>
            `;

            // 替换评分表单
            reviewForm.closest('.review-card').replaceWith(reviewedAlert);
        }
    }

    // 检查是否没有评价
    function checkEmptyReviews() {
        const commentsList = document.getElementById('commentsList');
        const reviews = commentsList.querySelectorAll('.comment:not(.reply)');

        if (reviews.length === 0) {
            commentsList.innerHTML = `
                <div class="text-center text-muted py-4">
                    <i class="fas fa-comments fa-2x mb-2"></i>
                    <p class="mb-0">暂无评价，成为第一个评价的人吧！</p>
                </div>
            `;
        }
    }

    // 动画效果函数
    function animateElement(element) {
        element.style.opacity = '0';
        element.style.transform = 'translateY(-10px)';

        setTimeout(() => {
            element.style.transition = 'all 0.3s ease-out';
            element.style.opacity = '1';
            element.style.transform = 'translateY(0)';
        }, 10);
    }

    function animateElementOut(element, callback) {
        element.style.transition = 'all 0.3s ease-out';
        element.style.opacity = '0';
        element.style.transform = 'translateY(-10px)';

        setTimeout(callback, 300);
    }

    function animateElementIn(element) {
        element.style.transition = 'all 0.3s ease-out';
        element.style.opacity = '1';
        element.style.transform = 'translateY(0)';
    }

    // 修复头像URL获取函数
    function getAvatarUrl(userData) {
    // 优先检查 avatar_url
    if (userData.avatar_url) {
        return userData.avatar_url;
    }
    // 检查 avatar 字符串
    if (userData.avatar && typeof userData.avatar === 'string') {
        return userData.avatar;
    }
    // 检查 avatar.url
    if (userData.avatar && userData.avatar.url) {
        return userData.avatar.url;
    }
    // 检查 profile.avatar
    if (userData.profile && userData.profile.avatar) {
        if (typeof userData.profile.avatar === 'string') {
            return userData.profile.avatar;
        }
        if (userData.profile.avatar.url) {
            return userData.profile.avatar.url;
        }
    }
    return null;
}


    // HTML转义函数
    function escapeHtml(unsafe) {
        return unsafe
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }

    // 报名功能
    function setupJoinButton() {
    const joinBtn = document.getElementById('join-btn');
    if (!joinBtn) return;

    joinBtn.addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();

        const activityId = this.getAttribute('data-activity-id');
        const button = this;

        // 检查用户是否登录
        {% if not user.is_authenticated %}
        window.location.href = "{% url 'login' %}?next={{ request.path }}";
        return;
        {% endif %}

        button.classList.add('loading');
        button.disabled = true;

        // 使用 Django 模板标签生成正确的 URL
        const joinUrl = "{% url 'join_activity' activity_id=0 %}".replace('0', activityId);
        console.log('报名URL:', joinUrl);

        fetch(joinUrl, {
            method: 'POST',
            headers: {
                'X-CSRFToken': '{{ csrf_token }}',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: new FormData()
        })
        .then(response => {
            console.log('响应状态:', response.status);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('报名响应:', data);
            if (data.success) {
                if (data.joined) {
                    button.innerHTML = '<i class="fas fa-user-check me-1"></i> 已报名';
                    button.classList.add('joined');
                    button.disabled = false;
                    showToast(data.message || '报名成功！', 'success');
                } else {
                    button.innerHTML = '<i class="fas fa-user-plus me-1"></i> 立即报名';
                    button.classList.remove('joined');
                    button.disabled = false;
                    showToast(data.message || '已取消报名', 'info');
                }

                // 更新参与人数显示
                updateParticipantsCount(data.current_participants, data.available_spots);
            } else {
                showToast(data.message || '操作失败', 'error');
                button.disabled = false;
            }
        })
        .catch(error => {
            console.error('报名错误:', error);
            showToast('网络错误，请重试', 'error');
            button.disabled = false;
        })
        .finally(() => {
            button.classList.remove('loading');
            button.disabled = false;
        });
    });
}

    // 更新参与人数显示
    function updateParticipantsCount(current, available) {
        const participantsElements = document.querySelectorAll('.current-participants, .available-spots');
        participantsElements.forEach(el => {
            if (el.classList.contains('current-participants')) {
                el.textContent = current;
            } else if (el.classList.contains('available-spots')) {
                el.textContent = available;
            }
        });

        // 更新进度条
        const progressBar = document.querySelector('.progress-bar');
        if (progressBar) {
            const percentage = (current / {{ activity.max_participants }} * 100);
            progressBar.style.width = `${percentage}%`;
        }
    }

    // 分享功能
    function shareToWeibo() {
        try {
            const url = encodeURIComponent(window.location.href);
            const title = encodeURIComponent(document.title);
            const shareUrl = `http://service.weibo.com/share/share.php?url=${url}&title=${title}`;
            window.open(shareUrl, '_blank', 'width=600,height=400');
        } catch (error) {
            console.error('微博分享错误:', error);
            showToast('分享失败，请重试', 'error');
        }
    }

    function shareToWechat() {
        if (copyLink()) {
            showToast('链接已复制，请粘贴到微信中分享', 'info');
        }
    }

    function shareToQQ() {
        try {
            const url = encodeURIComponent(window.location.href);
            const title = encodeURIComponent(document.title);
            const shareUrl = `https://connect.qq.com/widget/shareqq/index.html?url=${url}&title=${title}`;
            window.open(shareUrl, '_blank', 'width=600,height=400');
        } catch (error) {
            console.error('QQ分享错误:', error);
            showToast('分享失败，请重试', 'error');
        }
    }

    function shareToQzone() {
        try {
            const url = encodeURIComponent(window.location.href);
            const title = encodeURIComponent(document.title);
            const shareUrl = `https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=${url}&title=${title}`;
            window.open(shareUrl, '_blank', 'width=600,height=400');
        } catch (error) {
            console.error('QQ空间分享错误:', error);
            showToast('分享失败，请重试', 'error');
        }
    }

    function shareToDouban() {
        try {
            const url = encodeURIComponent(window.location.href);
            const title = encodeURIComponent(document.title);
            const shareUrl = `https://www.douban.com/share/service?href=${url}&name=${title}`;
            window.open(shareUrl, '_blank', 'width=600,height=400');
        } catch (error) {
            console.error('豆瓣分享错误:', error);
            showToast('分享失败，请重试', 'error');
        }
    }

    // 复制链接函数
    function copyLink() {
        const url = window.location.href;

        if (navigator.clipboard && navigator.clipboard.writeText) {
            return navigator.clipboard.writeText(url).then(() => {
                showToast('链接已复制到剪贴板', 'success');
                return true;
            }).catch(() => {
                return fallbackCopyLink(url);
            });
        } else {
            return fallbackCopyLink(url);
        }
    }

    function fallbackCopyLink(url) {
        try {
            const textArea = document.createElement('textarea');
            textArea.value = url;
            textArea.style.position = 'fixed';
            textArea.style.left = '-999999px';
            textArea.style.top = '-999999px';
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();

            const successful = document.execCommand('copy');
            document.body.removeChild(textArea);

            if (successful) {
                showToast('链接已复制到剪贴板', 'success');
                return true;
            } else {
                showToast('复制失败，请手动复制链接', 'error');
                return false;
            }
        } catch (err) {
            console.error('复制失败:', err);
            showToast('复制失败，请手动复制链接: ' + url, 'error');
            return false;
        }
    }

    // 显示提示消息
    function showToast(message, type = 'info') {
        // 移除现有的toast
        const existingToasts = document.querySelectorAll('.custom-toast');
        existingToasts.forEach(toast => toast.remove());

        // 创建toast元素
        const toast = document.createElement('div');
        toast.className = `custom-toast alert alert-${type} alert-dismissible fade show`;
        toast.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
            min-width: 250px;
        `;
        toast.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;

        document.body.appendChild(toast);

        // 3秒后自动消失
        setTimeout(() => {
            if (toast.parentNode) {
                toast.parentNode.removeChild(toast);
            }
        }, 3000);
    }

    // 修复私信功能
    function setupMessageFunction() {
    const messageForm = document.getElementById('messageForm');
    const messageList = document.getElementById('messageList');
    const followBtn = document.querySelector('.btn-follow');

    if (!messageForm || !messageList) {
        console.log('未找到私信表单或消息列表');
        return;
    }

    console.log('初始化私信功能');

    // 加载消息统计
    function loadMessageStats() {
        const getStatsUrl = "{% url 'get_message_stats' %}";

        fetch(`${getStatsUrl}?user_id=${currentOrganizerId}`, {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRFToken': '{{ csrf_token }}'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                updateUIWithStats(data.stats);
            }
        })
        .catch(error => {
            console.error('加载消息统计错误:', error);
        });
    }

    // 根据统计信息更新UI
    function updateUIWithStats(stats) {
        const messageInput = document.getElementById('messageContent');
        const sendButton = messageForm.querySelector('button[type="submit"]');
        const remainingInfo = document.getElementById('remainingMessages');

        // 创建或更新剩余消息显示
        if (!remainingInfo) {
            const newRemainingInfo = document.createElement('small');
            newRemainingInfo.id = 'remainingMessages';
            newRemainingInfo.className = 'message-limit-info';
            messageForm.querySelector('.d-flex').prepend(newRemainingInfo);
        }

        const remainingInfoElement = document.getElementById('remainingMessages');

        if (stats.can_send_unlimited) {
            // 互关，无限制
            messageInput.disabled = false;
            messageInput.placeholder = "输入您想说的话...";
            sendButton.disabled = false;
            remainingInfoElement.innerHTML = '<span class="text-success">互关好友，可无限聊天</span>';
        } else if (stats.remaining_messages > 0) {
            // 还有剩余消息次数
            messageInput.disabled = false;
            messageInput.placeholder = `还可发送 ${stats.remaining_messages} 条消息`;
            sendButton.disabled = false;

            if (!stats.is_following) {
                remainingInfoElement.innerHTML = `<span class="text-warning">未关注，还可发送 ${stats.remaining_messages} 条消息</span>`;
            } else {
                remainingInfoElement.innerHTML = `<span class="text-warning">对方未关注，还可发送 ${stats.remaining_messages} 条消息</span>`;
            }
        } else if (stats.remaining_messages === 0) {
            // 消息次数已用完
            messageInput.disabled = true;
            messageInput.placeholder = "消息次数已用完";
            sendButton.disabled = true;

            if (!stats.is_following) {
                remainingInfoElement.innerHTML = '<span class="text-danger">未关注，消息次数已用完。请先关注对方。</span>';
            } else {
                remainingInfoElement.innerHTML = '<span class="text-danger">对方未关注，消息次数已用完。</span>';
            }
        }

        // 更新关注按钮状态
        const followBtns = document.querySelectorAll('.btn-follow');
        followBtns.forEach(btn => {
            if (stats.is_following) {
                btn.innerHTML = '<i class="fas fa-check me-1"></i> 已关注';
                btn.classList.remove('btn-outline-primary');
                btn.classList.add('btn-primary');
            } else {
                btn.innerHTML = '<i class="fas fa-plus me-1"></i> 关注';
                btn.classList.remove('btn-primary');
                btn.classList.add('btn-outline-primary');
            }
        });
    }

    // 设置初始状态
    showInitialMessageState();
    loadMessageStats();

    // 发送消息
    messageForm.addEventListener('submit', function(e) {
        e.preventDefault();

        const contentInput = document.getElementById('messageContent');
        const content = contentInput.value.trim();
        const button = this.querySelector('button[type="submit"]');

        if (!content) {
            showToast('消息内容不能为空', 'error');
            return;
        }

        // 禁用按钮并显示加载状态
        const originalText = button.innerHTML;
        button.disabled = true;
        button.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>发送中...';

        // 使用JSON格式发送数据
        const sendMessageUrl = "{% url 'send_message' %}";
        const messageData = {
            'receiver_id': currentOrganizerId,
            'content': content
        };

        fetch(sendMessageUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': '{{ csrf_token }}',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify(messageData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                contentInput.value = '';
                showToast('消息发送成功', 'success');
                // 重新加载消息列表和统计
                window.loadMessages();
                loadMessageStats();
            } else {
                if (data.limit_reached) {
                    // 限制达到，更新UI
                    loadMessageStats();
                }
                showToast(data.message || '发送失败', 'error');
            }
        })
        .catch(error => {
            console.error('发送消息错误:', error);
            showToast('发送失败，请检查网络连接', 'error');
        })
        .finally(() => {
            // 恢复按钮状态
            button.disabled = false;
            button.innerHTML = originalText;
        });
    });

    // 关注按钮功能
    if (followBtn) {
        followBtn.addEventListener('click', function() {
            const button = this;
            const originalText = button.innerHTML;

            button.disabled = true;
            button.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>处理中...';

            const followUrl = "{% url 'toggle_follow' %}";
            const followData = {
                'user_id': currentOrganizerId
            };

            fetch(followUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': '{{ csrf_token }}',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify(followData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast(data.message, 'success');
                    // 更新消息统计
                    loadMessageStats();
                } else {
                    showToast(data.message || '操作失败', 'error');
                }
            })
            .catch(error => {
                console.error('关注操作错误:', error);
                showToast('操作失败，请重试', 'error');
            })
            .finally(() => {
                button.disabled = false;
                button.innerHTML = originalText;
            });
        });
    }

    // 模态框显示时加载消息和统计
    const messageModal = document.getElementById('messageModal');
    if (messageModal) {
        messageModal.addEventListener('show.bs.modal', function() {
            console.log('私信模态框打开');
            // 延迟加载，确保模态框完全打开
            setTimeout(() => {
                window.loadMessages();
                loadMessageStats();
            }, 300);
        });

        messageModal.addEventListener('hidden.bs.modal', function() {
            const contentInput = document.getElementById('messageContent');
            if (contentInput) {
                contentInput.value = '';
            }
        });
    }
}
    // 全局消息相关函数
let currentOrganizerId = {{ activity.organizer.id }};

// 全局可访问的加载消息函数 - 根据您的视图调整
window.loadMessages = function() {
    const messageList = document.getElementById('messageList');
    if (!messageList) return;

    console.log('加载消息，组织者ID:', currentOrganizerId);

    // 显示加载状态
    messageList.innerHTML = `
        <div class="text-center text-muted py-4">
            <i class="fas fa-spinner fa-spin fa-2x mb-2"></i>
            <p class="mb-0">加载消息中...</p>
        </div>
    `;

    // 使用正确的参数名 user_id（根据您的视图）
    const getMessagesUrl = "{% url 'get_messages' %}";

    fetch(`${getMessagesUrl}?user_id=${currentOrganizerId}`, {
        method: 'GET',
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRFToken': '{{ csrf_token }}'
        }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('收到消息数据:', data);
        if (data.success && data.messages) {
            renderMessages(data.messages);
        } else {
            showInitialMessageState();
            if (data.message) {
                console.log('API返回消息:', data.message);
            }
        }
    })
    .catch(error => {
        console.error('加载消息错误:', error);
        showErrorMessageState('加载消息失败，请稍后重试');
    });
};

// 渲染消息列表 - 根据您的数据结构调整
function renderMessages(messages) {
    const messageList = document.getElementById('messageList');
    if (!messageList) return;

    if (!messages || messages.length === 0) {
        showInitialMessageState();
        return;
    }

    let messagesHTML = '';
    messages.forEach(message => {
        // 使用 is_own 而不是 is_sender
        const messageClass = message.is_own ? 'message-sender' : 'message-receiver';
        messagesHTML += `
            <div class="message-item ${messageClass}">
                <div class="message-content">${escapeHtml(message.content)}</div>
                <div class="message-time">${message.created_at}</div>
            </div>
        `;
    });

    messageList.innerHTML = messagesHTML;
    messageList.scrollTop = messageList.scrollHeight;
}

// 显示初始状态
function showInitialMessageState() {
    const messageList = document.getElementById('messageList');
    if (!messageList) return;

    messageList.innerHTML = `
        <div class="text-center text-muted py-4">
            <i class="fas fa-comments fa-2x mb-2"></i>
            <p class="mb-0">开始与{{ activity.organizer.username }}的对话</p>
            <small class="text-muted">发送消息开始聊天</small>
        </div>
    `;
}

// 显示错误状态
function showErrorMessageState(message) {
    const messageList = document.getElementById('messageList');
    if (!messageList) return;

    messageList.innerHTML = `
        <div class="text-center text-muted py-4">
            <i class="fas fa-exclamation-triangle fa-2x mb-2"></i>
            <p class="mb-0">${message}</p>
            <button class="btn btn-sm btn-primary mt-2" onclick="window.loadMessages()">重试</button>
        </div>
    `;
}

    // 倒计时功能
    function updateCountdown() {
        const startTime = new Date('{{ activity.start_time|date:"c" }}').getTime();
        const now = new Date().getTime();
        const distance = startTime - now;

        if (distance > 0) {
            const days = Math.floor(distance / (1000 * 60 * 60 * 24));
            const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((distance % (1000 * 60)) / 1000);

            document.getElementById("countdown-timer").innerHTML =
                `${days}天 ${hours}小时 ${minutes}分 ${seconds}秒`;
        } else {
            // 活动已开始，刷新页面更新状态
            clearInterval(countdownTimer);
            location.reload();
        }
    }

    // 如果活动即将开始，启动倒计时
    {% if activity.time_based_status == 'upcoming' %}
    let countdownTimer = setInterval(updateCountdown, 1000);
    updateCountdown(); // 立即执行一次
    {% endif %}

    // 活动状态自动更新
    function checkActivityStatus() {
        // 每5分钟检查一次活动状态
        setInterval(() => {
            const activityId = {{ activity.id }};
            fetch(`/api/activity/${activityId}/status/`)
                .then(response => {
                    if (!response.ok) return { status_changed: false };
                    return response.json();
                })
                .then(data => {
                    if (data.status_changed) {
                        location.reload();
                    }
                })
                .catch(error => console.error('状态检查失败:', error));
        }, 300000);
    }

    // 如果活动正在进行中或即将开始，启动状态检查
    {% if activity.time_based_status == 'upcoming' or activity.time_based_status == 'ongoing' %}
    checkActivityStatus();
    {% endif %}

    // 在DOM加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        console.log('活动详情页加载完成');
        setupJoinButton();
        initCommentFunctions();
        setupMessageFunction();

        // 调试信息
        const joinBtn = document.getElementById('join-btn');
        if (joinBtn) {
            console.log('报名按钮状态:', {
                authenticated: {% if user.is_authenticated %}true{% else %}false{% endif %},
                isOrganizer: {% if user == activity.organizer %}true{% else %}false{% endif %},
                isFull: {% if activity.is_full %}true{% else %}false{% endif %},
                userJoined: {% if user_joined %}true{% else %}false{% endif %}
            });
        }
    });

    // 图片加载错误处理函数
function handleImageError(img, defaultImage) {
    const defaultImages = {
        'activity': 'https://res.cloudinary.com/dqfqah1dn/image/upload/v1640997659/meetlocal/default-activity_zkvqjp.jpg',
        'avatar': 'https://res.cloudinary.com/dqfqah1dn/image/upload/v1640997659/meetlocal/default-avatar_qwq8xj.png'
    };

    img.onerror = null;
    img.src = defaultImages[defaultImage] || defaultImages['activity'];
}

// 头像加载错误处理
function handleAvatarError(img) {
    const parent = img.parentElement;
    const username = img.alt;
    if (username) {
        parent.innerHTML = username.charAt(0).toUpperCase();
        parent.style.background = 'linear-gradient(135deg, var(--primary), var(--secondary))';
        parent.style.color = 'white';
        parent.style.display = 'flex';
        parent.style.alignItems = 'center';
        parent.style.justifyContent = 'center';
        parent.style.fontWeight = '600';
    }
    img.style.display = 'none';
}

</script>
{% endblock %}